<template>
	<view class="index-wrap" :class="{'pb144':replyInputShow}">
		<!-- 头部 -->
		<index-top @avatarClk="showSideNavBar"></index-top>

		<!-- 侧边栏导航 -->
		<side-nav-bar @maskClk="hideSideNavBar" :show="sideNavBarShow"></side-nav-bar>

		<!-- 评论列表 -->
		<view class="comment-list">
			<commentItem @commentClk="commentItemClk(item,index)" @toReply="showReplyInput(item)" v-for="(item,index) in evaluatelist"
				:key="item.id" :commentDataOrigin="item"></commentItem>
		</view>

		<!-- 新用户提醒弹窗 -->
		<alertPop :title="'温馨提示'" :content="'本平台的一切内容仅来自您的好友，在您添加好友的过程中，请谨慎操作。'" :btnText="'我知道了'"
			@maskClk="closeNewUserTipsPop" @btnClk="closeNewUserTipsPop" v-show="newUserTipsPopShow">
		</alertPop>

		<!-- 消息提示 -->
		<index-toast ref="toast"></index-toast>

		<!-- 添加好友申请 -->
		<friend-apply-pop ref="friendApplyPop"></friend-apply-pop>

		<!-- 分享评论申请 -->
		<share-comment-pop ref="shareCommentPop"></share-comment-pop>

		<!-- 被评人好友申请 -->
		<expert-friend-apply-pop ref="expertFriendApplyPop"></expert-friend-apply-pop>

		<!-- 评论 -->
		<replyCommentInput v-if="replyInputShow" :autoFocus="true" @blur="hideReplyInput" @submit="submitReply">
		</replyCommentInput>

		<view class="more-tips">
			<text v-show="loadingMoreTipsShow">更多加载中...</text>
			<text v-show="noMoreTipsShow">没有更多啦~</text>
			<text v-show="noDataTipsShow">暂无评论信息</text>
		</view>
	</view>

</template>

<script>
	import indexTop from './indexTop.vue'
	import sideNavBar from './sideNavBar.vue'
	import indexToast from '../../components/indexToast/indexToast.vue'
	import friendApplyPop from '../../components/friendApplyPop/friendApplyPop.vue'
	import shareCommentPop from '../../components/shareCommentPop/shareCommentPop.vue'
	import expertFriendApplyPop from '../../components/expertFriendApplyPop/expertFriendApplyPop.vue'
	
	import IMService from "../../sdk/imservice.js"
	import { mapState } from "vuex"
	export default {
		components: {
			indexTop,
			sideNavBar,
			indexToast,
			friendApplyPop,
			shareCommentPop,
			expertFriendApplyPop
		},
		computed: {
		  ...mapState(['userInfo','fromUserId','unReadMsgNum','unReadChatNum','token','fromVirtualId']),
		},
		data() {
			return {
				sideNavBarShow: false,
				newUserTipsPopShow: false,
				replyInputShow: false,
				loadingMoreTipsShow: false,
				noMoreTipsShow: false,
				noDataTipsShow: false,
				pageNo: 1,
				pageSize: 5,
				evaluatelist: []
			}
		},
		onShow() {
			if(this.token){
				this.getNoReadMsg()
				this.execGetNoReadMsgLoop()
			}
			if(this.clickCommentObj){
				// 局部刷新列表
				this.getEvaluateItemById(this.clickCommentObj)
			}else{
			   this.initGetList()
			}
		},
		onHide(){
            this.stopTimer()
		},
		onLoad(options) {
			if (options.fromUserId) {
				this.$store.commit('setFromUserId', options.fromUserId)
			}
			// if(options.virtualId){
			//     this.$store.commit('setFromVirtualId', options.virtualId)
			// }
		},
		onPullDownRefresh() {
			if(!this.token){
				// 未登录
				uni.stopPullDownRefresh()
			}else{
				this.initGetList()
			}
		},
		onReachBottom() {
			if (this.noMoreTipsShow || this.loadingMoreTipsShow || !this.token) return
			this.loadingMoreTipsShow = true
			this.getEvaluatelist().then((res) => {
				if(!res) return
				this.loadingMoreTipsShow = false
				if (res.rows && res.rows.length) {
					this.evaluatelist = [...this.evaluatelist, ...res.rows]
				} else {
					this.noMoreTipsShow = true
				}
			})
		},

		methods: {
			initGetList() {
				this.pageNo = 1
				this.noMoreTipsShow = false
				this.noDataTipsShow = false
				this.loadingMoreTipsShow = false
				uni.showLoading({ mask: true })
				this.getEvaluatelist().then((res) => {
					if(!res) return
					this.checkFromUserId()
					this.initGoEasy()
					if (!res.rows || res.rows.length === 0) {
						this.noDataTipsShow = true
					} else if (res.rows.length < this.pageSize) {
						this.noMoreTipsShow = true
					}
					this.evaluatelist = res.rows
					uni.stopPullDownRefresh()
				})
			},
			getEvaluatelist() {
				return this.$api.getEvaluatelist({
					pageNo: this.pageNo,
					pageSize: this.pageSize
				}).then((res) => {
					this.pageNo++
					return res
				}).catch(()=>{
					this.$store.commit('setUserToken','')
					uni.setStorageSync('token', '');
					this.sideNavBarShow = false
					this.getCommonEvaluatelist()
				})
			},
			
			// 不需要登录的点评列表
			getCommonEvaluatelist(){
				this.$api.getCommonEvaluatelist({
					pageNo: 1,
					pageSize: 10
				}).then((res) => {
					this.evaluatelist = res.rows
				})
			},
			
			getEvaluateItemById({id,index}){
				this.$api.getEvaluateDetail(id).then((res)=>{
					this.evaluatelist.splice(index,1,res)
					this.clickCommentObj = null
				})
			},
			showSideNavBar() {
				this.$api.getUserInfo().then((res) => {
					this.$store.commit('setUserInfo',res)
				})
				this.sideNavBarShow = true
			},
			hideSideNavBar() {
				this.sideNavBarShow = false
			},
			commentItemClk(data,index) {
				if(!this.token){
				    uni.navigateTo({
					    url: '/pages/login/index'
				    })
					return
				}
				this.clickCommentObj = { id:data.id, index }
				uni.navigateTo({
					url: `/pages/commentDetail/index?id=${data.id}`
				})

				// this.$refs.toast.show({
				// 	type: 'danger',
				// 	imgs: ['http://i0.hdslb.com/bfs/article/878a6c57bed136d9d176a6eb8289a04787b126bf.jpg',
				// 		'http://i0.hdslb.com/bfs/article/878a6c57bed136d9d176a6eb8289a04787b126bf.jpg',
				// 		'http://i0.hdslb.com/bfs/article/878a6c57bed136d9d176a6eb8289a04787b126bf.jpg'
				// 	],
				// 	text: `新增3条评论`
				// })

				// this.$refs.toast.show({
				// 	type: 'success',
				// 	text: '登录成功'
				// })

				// this.$refs.friendApplyPop.show({})

				// this.$refs.shareCommentPop.show({})

				// this.$refs.expertFriendApplyPop.show({})
			},
			closeNewUserTipsPop() {
				this.newUserTipsPopShow = false
			},
			showReplyInput() {
				this.replyInputShow = true
			},
			hideReplyInput() {
				this.replyInputShow = false
			},
			submitReply(text) {
				this.replyInputShow = false
			},
			checkFromUserId() {
				const fromUserId = this.fromUserId
				const userId = this.userInfo.id
				if (fromUserId && fromUserId * 1 !== userId * 1) {
					this.getFromUserInfo(fromUserId,userId)
				}
				// if(this.fromVirtualId){
				// 	this.bindVirtualId(this.fromVirtualId,userId)
				// }
			},
			getFromUserInfo(fromUserId,userId) {
				this.$api.getUserInfoById(fromUserId).then((res) => {
					const data = {
						fromUserId: fromUserId * 1,
						fromType: "微信分享",
						fromDesc: `通过微信分享添加，请确认对方身份`,
						fromRemark: `${res.nickName}请求添加您为好友`,
						toUserId: userId * 1
					}
					this.$api.sendAddFriendApply(data).then(() => {
						this.$store.commit('setFromUserId', '')
						uni.showToast({
							title: '您收到一条好友申请',
							icon: 'none'
						})
						setTimeout(() => {
							uni.navigateTo({
								url: `/pages/message/index`
							})
						}, 1500)
					})
				})
			},
			// bindVirtualId(virtualId,userId){
            //     this.$api.setVirtualIdToUser({
			// 		virtualId: virtualId * 1,
            //         userId: userId * 1
			// 	}).then(()=>{
			// 		this.$store.commit('setFromVirtualId', '')
			// 	})
			// },
			initGoEasy(){
				const userInfo = this.userInfo
				let currentUser = {
					"uuid": userInfo.id + '',
					"name": userInfo.nickName,
					"avatar": this.getImgUrl(userInfo.avatar)
				}
				if (this.goEasy.getConnectionStatus() === 'disconnected') {
					getApp().globalData.imService = new IMService(this.goEasy, this.GoEasy);
					getApp().globalData.imService.connect(currentUser);
				}
				
				this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {
					this.$store.commit('setUnReadChatNum',content.unreadTotal)
				})
				this.goEasy.im.latestConversations({
					onSuccess: (result) => {
						let content = result.content;
						this.$store.commit('setUnReadChatNum',content.unreadTotal)
					}
				})
			},
			getNoReadMsg(){
				this.$store.dispatch('getNoReadMsg')
			},
			execGetNoReadMsgLoop(){
				this.getNoReadMsgLoopTimer = setTimeout(()=>{
                    if(this.token){
						this.getNoReadMsg()
						this.execGetNoReadMsgLoop()
					}
				},5000)
			},
			stopTimer(){
				if(this.getNoReadMsgLoopTimer){
					clearTimeout(this.getNoReadMsgLoopTimer)
					this.getNoReadMsgLoopTimer = null
				}
			}
			
		}
	}
</script>

<style>
	page {
		background-color: #F3F7FD;
	}
</style>
<style lang="less" scoped>
	.comment-list {
		width: 690rpx;
		margin: 0 auto;
		// padding-bottom: 40rpx;
	}

	.index-wrap {
		&.pb144 {
			padding-bottom: 144rpx;
		}
	}

	.more-tips {
		height: 80rpx;
		font-size: 26rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #aaa;
	}
</style>
